function toUpperCase(str) {
  if(typeof str === 'string') {
    return str.toUpperCase()
  }
}

function hasOwn(obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key)
}


function request( options = {} ){
  const url = options.url
  const method = toUpperCase(options.method) || 'GET'
  const headers = Object.assign({
    'Accept': 'text/plain, *'
  }, options.headers || {})

  const data = options.data

  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    xhr.onreadystatechange = function() {
      if(xhr.readyState === 4) {
        if(xhr.status === 200) {
          resolve(xhr.responseText)
        } else {
          reject(xhr.responseText)
        }
      }
    }

    xhr.onerror = function(e) {
      console.error(e)
    }

    xhr.open(method, url)

    //setRequestHeader  必须在open之后，send之前

    for(let key of Object.keys(headers)) {
      if(hasOwn(headers, key)) {
        xhr.setRequestHeader(key, headers[key])
      }
    }


    if(method !== 'GET') {
      xhr.send(data)
    } else {
      xhr.send()
    }
  })
}

export default request

